import  os          ,zipfile        ,traceback      ,string
import  xbmc        ,xbmcgui
from re import search as reSearch

HOME_DIR        =   os.getcwd().replace(";","")+"\\"        # get homedirectory for the script

def BackupData()    :
    try     :
        TmpFile     =   None
        TmpName     =   HOME_DIR + 'Backup.zip'
        NewName     =   HOME_DIR + 'New.zip'

        ## Remove the file if it exists.
        if os.path.isfile(TmpName)  :
            os.remove(TmpName)

        ## Open new File.
        TmpFile     =   zipfile.ZipFile(TmpName,'w')

        ## Walk through dirs and get all the files needed for the backup.
        ## Ignore the files,controllers and sites directories and also the backup.zip file.
        for dirname,blank,elements in os.walk(HOME_DIR):
            for i in elements :
                FullPath =  os.path.join(dirname,i)
                if      os.path.isfile(FullPath)                    and         \
                        i != 'Backup.zip'                           and         \
                        i != 'New.zip'                              and         \
                        i != 'update.py'                            and         \
                        ( not reSearch('files',dirname) )           and         \
                        ( not reSearch('sites',dirname) )           and         \
                        ( not reSearch('controllers',dirname) )                 :
                        
                    ## File is valid so write it out to the archive.
                    TmpFile.write(FullPath)

        ## Close the Archive file we have finished it now.
        TmpFile.close()
        return True
    except  :
        traceback.print_exc()
        if TmpFile != None  :
            TmpFile.close()
            os.remove(TmpName)
        return False
        
def RestoreData()        :
    try     :
        TmpFile     =   None
        NewName     =   HOME_DIR + 'New.zip'

        ## Open new File.
        TmpFile     =   zipfile.ZipFile(NewName,'r')
        if TmpFile.testzip() == None    :
            print 'File is Good..'
            for i in TmpFile.namelist() :
                FullPath    =   os.path.join(HOME_DIR,i)
                if  len(i.split('.')) ==    1       :
                    if not os.path.isdir(FullPath)  :
                        os.mkdir(FullPath)
                else                                :
                    FileData    =   TmpFile.read(i)
                    try     :
                        reWrite     =   None
                        reWrite     =   open(FullPath,'wb')
                        reWrite.write(FileData)
                        reWrite.close()
                    except  :
                        traceback.print_exc()
                        if reWrite != None  :
                            reWrite.close()
                print 'In Archive : '+ str(FullPath)

        TmpFile.close()
        return True
    except  :
        traceback.print_exc()
        if TmpFile != None  :
            TmpFile.close()
        return False

Progress        =   xbmcgui.DialogProgress()
Header          =   'Updating Core'
Msg1            =   '--Updating Core System'
Msg2            =   '--Backed Up Files to Backup.zip'
Msg3            =   '--Extracted New Files'

AllGood         =   False
Progress.create(Header,Msg1)
if ( BackupData() ) :
    Progress.update(33,Msg1,Msg2)
    if ( RestoreData() )    :
        Progress.update(66,Msg1,Msg2,Msg3)
        AllGood     =   True
        os.remove(HOME_DIR + 'New.zip')

Progress.close()
if ( AllGood )  :
    xbmc.executescript(HOME_DIR + 'default.py')    
